package com.blueocean_health.care.management.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.blueocean_health.care.management.common.base.string.StringUtils;
import com.blueocean_health.care.management.domain.base.SysResult;
import com.blueocean_health.care.management.domain.base.SysResultByPage;
import com.blueocean_health.care.management.domain.base.UserAccount;
import com.blueocean_health.care.management.domain.base.UserToken;
import com.blueocean_health.care.management.domain.dto.UserAccountDto;
import com.blueocean_health.care.management.domain.vo.ModuleVo;
import com.blueocean_health.care.management.domain.vo.OrgAndProjectTreeParam;
import com.blueocean_health.care.management.domain.vo.UserAccountVo;
import com.blueocean_health.care.management.domain.vo.UserVo;
import com.blueocean_health.care.management.mapper.UserAccountMapper;
import com.blueocean_health.care.management.mapper.UserTokenMapper;
import com.blueocean_health.care.management.service.OrganizationService;
import com.blueocean_health.care.management.service.PowerService;
import com.blueocean_health.care.management.service.RoleService;
import com.blueocean_health.care.management.service.UserAccountService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * 用户信息 2018年4月17日14:13:21
 * @author wuyanli
 *
 */
@Service
public class UserAccountServiceImpl implements UserAccountService{
	
	@Autowired
	private UserAccountMapper userDao;
	@Autowired
	private UserTokenMapper userTokenMapper;
	@Autowired
	private RoleService roleService;
	@Autowired
	private OrganizationService organizationService;
	@Autowired
	private PowerService powerService;
	
	@Value("${service.address}")
	private String SERVICEADDRESS;
	
	@Override
	@SuppressWarnings("unused")
	public UserAccountDto getUserAccountInfo(Map<String, String> map) {
		UserAccountDto userAccountInfo = userDao.getUserAccountInfo(map);
		return null;
	}


	/**
	 * 新增用户
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public SysResult addUser(UserAccount user) {
		UserAccountDto userByUserName = userDao.getUserByUserName(user.getUserName(), null);
		if(!StringUtils.isEmpty(userByUserName)){
			return SysResult.error("该用户名已存在，请修改");
		}
		 user.setPassword(DigestUtils.md5Hex(user.getPassword()));
		int addUser = userDao.addUser(user);
		if(addUser <= 0){
			return SysResult.error();
		}
		return SysResult.ok();
	}

	/**
	 * 编辑用户
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public SysResult updateUser(UserAccount user) {
		UserAccountDto userByUserName = userDao.getUserByUserName(user.getUserName(), user.getUserId()+"");
		if(!StringUtils.isEmpty(userByUserName)){
			return SysResult.error("该用户名已存在，请修改");
		}
		int updateUser = userDao.updateUser(user);
		if(updateUser <= 0){
			return SysResult.error();
		}
		return SysResult.ok();
	}

	/**
	 * 删除用户
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public SysResult deleteUser(String userId) {
		Map<String,Object> paramsMap = new HashMap<>();
		paramsMap.put("userId", userId);
		paramsMap.put("condition", false);
		List<Map<String, String>> roleList = roleService.findRoleByUserId(paramsMap);
		if (!roleList.isEmpty()) {
			return SysResult.error("该用户已关联角色，现无法删除。");
		}
		int deleteUser = userDao.deleteUser(userId);
		if(deleteUser <= 0){
			return SysResult.error();
		}
		return SysResult.ok();
	}

	/**
	 * 重置密码  2018年4月17日15:20:59
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public SysResult updatePassword(Map<String,String> map) {
		String password = DigestUtils.md5Hex(map.get("password"));
		map.put("password", password);
		int updatePassword = userDao.resetPassword(map);
		if(updatePassword <= 0){
			return SysResult.error();
		}
		return SysResult.ok();
	}

	/**
	 * 查看用户关联角色
	 */
	@Override
	public SysResult queryRole(String userId) {
		Map<String,Object> paramsMap = new HashMap<>();
		paramsMap.put("userId", userId);
		paramsMap.put("condition", true);
		List<Map<String, String>> roleList = roleService.findRoleByUserId(paramsMap);
		return SysResult.ok(roleList);
	}

	/**
	 * 查看用户详情
	 */
	@Override
	public SysResult query(String userId) {
		if (StringUtils.isEmpty(userId)) {
			return SysResult.ok("参数不能为空");
		}
		UserAccountVo userAccountVo =  userDao.query(userId);
		return SysResult.ok(userAccountVo);
	}

	/**
	 * 查看用户列表
	 */
	@Override
	public SysResult list(Map<String, Object> map) {
		Integer page = (Integer)map.get("page");
		Integer pageSize = (Integer)map.get("pageSize");
		PageHelper.startPage(page, pageSize);
		List<UserAccountVo> userAccountVoList = userDao.list(map);
		PageInfo<UserAccountVo> pageInfo = new PageInfo<>(userAccountVoList);
		return SysResultByPage.ok(pageInfo.getList(), pageInfo.getTotal());
	}

	/**
	 * 当前用户组织下的组织/项目架构图
	 */
	@Override
	public SysResult teamList() {
		List<OrgAndProjectTreeParam> list = organizationService.findAllSubOrgAndProjectByOrgId();
		return SysResult.ok(list);
	}
	/**
	 * 登录
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public UserVo login(UserAccount userAccount) {
		String password = userAccount.getPassword();
		// 加密
		userAccount.setPassword(DigestUtils.md5Hex(password));
		UserAccount currentUserInfo = userDao.getCurrentUserInfo(userAccount);
		if (currentUserInfo==null) {
			return null;
		}
		// 获得登录名对应的所有组织/项目集合
		Map<String,Object> paramsMap = new HashMap<>();
		paramsMap.put("userId", currentUserInfo.getUserId());
		paramsMap.put("condition", true);
		List<Map<String, String>> roleList = roleService.findIdentityByUserId(paramsMap);
		// 保存token信息
		UserToken userToken = saveUserToken(currentUserInfo.getUserId(), roleList);
		// 返回数据
		UserVo userVo = new UserVo();
		userVo.setUserId(currentUserInfo.getUserId());
		userVo.setUserName(currentUserInfo.getUserName());
		userVo.setUserRealName(currentUserInfo.getUserRealName());
		userVo.setToken(userToken.getToken());
		userVo.setOrgOrProjectList(roleList);
		userVo.setAvatar("defaultUser.jpg");
		userVo.setAvatar(SERVICEADDRESS+"defaultUser.jpg");
		userVo.setTeamLogo(SERVICEADDRESS+"hospitalLogo.png");
		return userVo;
	}
	
	/**
	 * 保存token信息
	 * @param userId
	 * @param roleList
	 */
	private UserToken saveUserToken(Integer userId, List<Map<String, String>> roleList) {
		UserToken userToken = new UserToken();
		userToken.setUserId(userId+"");
		if (roleList.size()==1) {
			userToken.setTeamId(roleList.get(0).get("teamId"));
		}
		userToken.setToken(UUID.randomUUID().toString());
		userToken.setIsActive(1);
		userToken.setIsPhone(0);
		userToken.setCreateTime(new Date());
		int count = userTokenMapper.insert(userToken);
		if (count<=0) {
			return null;
		}
		return userToken;
	}

	/**
	 * 通过token 查询用户信息
	 */
	@Override
	public UserAccount getUserInfoByToken(String token) {
		UserToken userToken = userTokenMapper.getTokenByToken(token);
		if(userToken == null){
			return null;
		}
		String userId = userToken.getUserId();
		UserAccount user = new UserAccount();
		user.setUserId(Integer.parseInt(userId));
		// 查询用户详情
		UserAccountVo userAccountVo = userDao.query(userId);
		// 返回数据
		UserAccount currentUserInfo = new UserAccount();
		currentUserInfo.setUserId(userAccountVo.getUserId());
		currentUserInfo.setUserName(userAccountVo.getUserName());
		currentUserInfo.setUserRealName(userAccountVo.getUserRealName());
		if (StringUtils.isEmpty(userAccountVo.getEnableStatus())) {
			currentUserInfo.setEnableStatus(Integer.parseInt(userAccountVo.getEnableStatus()));
		}
		if (!StringUtils.isEmpty(userAccountVo.getUserSource())) {
			currentUserInfo.setUserSource(Integer.parseInt(userAccountVo.getUserSource()));
		}
		// 用户真实选择的组织
		currentUserInfo.setTeamId(userToken.getTeamId()); 
		return currentUserInfo;
	}

	/**
	 * 登录后多身份选择
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public SysResult selectIdentity(Map<String, String> paramsMap) {
    	// 将选择的组织/项目保存到对应token中
    	int count = userTokenMapper.updateTokenTeamIdByToken(paramsMap);
    	if (count<=0) {
    		return SysResult.error("更新token失败");
    	}
    	UserToken token = userTokenMapper.getTokenByToken(paramsMap.get("token"));
    	// 权限列表
    	List<ModuleVo> permissionList = new ArrayList<>();
		// 根据userId和teamId查找权限列表
		permissionList = powerService.getUserPermissions(token.getUserId(), token.getTeamId());
    	Map<String,Object> data = new HashMap<>();
    	data.put("permissions",permissionList);
		return SysResult.ok(data);
	}
	
}
